import java.util.ArrayList;
import java.util.List;

public class Match {
    private int id;
    private Team homeTeam;
    private Team awayTeam;
    private String status;    // 状态：进行中、已结束
    private Team winner;      // 获胜队伍
    private List<SetScore> sets; // 各局比分

    public Match(int id, Team homeTeam, Team awayTeam) {
        this.id = id;
        this.homeTeam = homeTeam;
        this.awayTeam = awayTeam;
        this.status = "进行中";
        this.winner = null;
        this.sets = new ArrayList<>();
    }

    // Getters and Setters
    public int getId() {
        return id;
    }

    public Team getHomeTeam() {
        return homeTeam;
    }

    public Team getAwayTeam() {
        return awayTeam;
    }

    public String getStatus() {
        return status;
    }

    public Team getWinner() {
        return winner;
    }

    public List<SetScore> getSets() {
        return sets;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setWinner(Team winner) {
        this.winner = winner;
    }

    // 添加一局比分
    public void addSetScore(SetScore setScore) {
        sets.add(setScore);

        // 更新队伍得分
        homeTeam.incrementPointsFor(setScore.getHomeScore());
        homeTeam.incrementPointsAgainst(setScore.getAwayScore());
        awayTeam.incrementPointsFor(setScore.getAwayScore());
        awayTeam.incrementPointsAgainst(setScore.getHomeScore());

        // 检查比赛是否结束
        checkMatchStatus();
    }

    // 检查比赛状态
    private void checkMatchStatus() {
        if (status.equals("已结束")) return;

        int homeSetsWon = 0;
        int awaySetsWon = 0;

        for (SetScore set : sets) {
            if (set.getWinner() == homeTeam) {
                homeSetsWon++;
            } else {
                awaySetsWon++;
            }
        }

        // 更新队伍胜局数
        homeTeam.incrementSetsWon(homeSetsWon - homeTeam.getSetsWon());
        homeTeam.incrementSetsLost(awaySetsWon - homeTeam.getSetsLost());
        awayTeam.incrementSetsWon(awaySetsWon - awayTeam.getSetsWon());
        awayTeam.incrementSetsLost(homeSetsWon - awayTeam.getSetsLost());

//        判断比赛是否结束（一方赢了3局）
        if (homeSetsWon >= 3) {
            status = "已结束";
            winner = homeTeam;
            homeTeam.incrementWins();
            awayTeam.incrementLosses();
        } else if (awaySetsWon >= 3) {
            status = "已结束";
            winner = awayTeam;
            awayTeam.incrementWins();
            homeTeam.incrementLosses();
        }
    }
}



























